package cn.sh.basic.controller;

import cn.sh.basic.util.AjaxResult;
import cn.sh.basic.util.FastdfsUtil;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;

@RestController
@RequestMapping("/fastdfs")
public class FileUploadController {

    @PostMapping("/upload")
    public AjaxResult upload(@RequestPart(value = "file",required = true) MultipartFile file){
        try {
            String fileName = file.getOriginalFilename();
            String extName = fileName.substring(fileName.lastIndexOf(".") + 1);
            String result = FastdfsUtil.upload(file.getBytes(), extName);
            return AjaxResult.me().setResultObj(result);
        } catch (IOException e) {
            e.printStackTrace();
            return AjaxResult.me().setSuccess(false).setMesssage("系统繁忙");
        }
    }

    @DeleteMapping
    public AjaxResult delete(@RequestParam(value = "path",required = true) String path){
        //   /group1/M00/01/28/CgAIC2Ls0xyARkv7AAD1Sgb3qiI779.jpg
        try {
            String pathTmp = path.substring(1); // group1/M00/01/28/CgAIC2Ls0xyARkv7AAD1Sgb3qiI779.jpg
            String groupName =  pathTmp.substring(0, pathTmp.indexOf("/")); //goup1
            String remotePath = pathTmp.substring(pathTmp.indexOf("/")+1);// M00/01/28/CgAIC2Ls0xyARkv7AAD1Sgb3qiI779.jpg
            FastdfsUtil.delete(groupName,remotePath);
            return AjaxResult.me();
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.me().setSuccess(false).setMesssage("系统繁忙");
        }
    }
}
